package com.hxcoder.utils;

import com.sun.mail.util.MailSSLSocketFactory;
import org.apache.log4j.Logger;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;

import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;
import java.util.Properties;

public class MAILUtils {

    private static Logger log = Logger.getLogger(MAILUtils.class);

    public static final String VALIDATE_CODE = "SMS_159620392";//发送短信验证码
    public static final String ORDER_NOTICE = "SMS_159771588";//体检预约成功通知

    public static void sendMailCode(String templateCode, String param, String toMali) {

        try {
            String from = "星空健康";//发件人昵称展示
            String[] to = {toMali};//接收邮箱
            String host = "smtp.163.com";//163企业邮箱smtp
            String username = "19808183989@163.com";//发件人邮箱
            String password = "RYOTZSZEQHZUSVSS";//发件人邮箱密码
            String subject = "";//邮件主题
            String text = "";//邮件内容
            //发送短信验证码
            if (templateCode.equals(VALIDATE_CODE)) {
                subject = "验证码";
                text = "您好，你的验证码是：" + "<h2>" + param + "</h2>";
            } else { //体检预约成功通知
                subject = "体检预约成功通知";
                text = "您好，你已成功预约 " + param + " 的身体检查";
            }
            //设置服务器验证信息
            Properties prop = new Properties();
            prop.setProperty("mail.smtp.auth", "true");
            prop.setProperty("mail.smtp.timeout", "994");
            MailSSLSocketFactory sf = new MailSSLSocketFactory();// SSL加密
            sf.setTrustAllHosts(true); // 设置信任所有的主机
            prop.put("mail.smtp.ssl.enable", "true");
            prop.put("mail.smtp.ssl.socketFactory", sf);
            //设置邮件内容
            JavaMailSenderImpl javaMailSend = new JavaMailSenderImpl();
            MimeMessage message = javaMailSend.createMimeMessage();
            MimeMessageHelper messageHelper = new MimeMessageHelper(message, true, "utf-8");
            String nick = MimeUtility.encodeText(from);//设置昵称
            messageHelper.setFrom(new InternetAddress(nick + " <" + username + ">"));//邮件发送者
            messageHelper.setTo(to);
            messageHelper.setSubject(subject);
            messageHelper.setText(text, true);
            //设置邮件服务器登录信息
            javaMailSend.setHost(host);
            javaMailSend.setUsername(username);
            javaMailSend.setPassword(password);
            javaMailSend.setJavaMailProperties(prop);
            log.info("mailValidateCode：" + text);
            javaMailSend.send(message);
        } catch (Exception e) {
            log.error(e);
            e.printStackTrace();
        }
    }
}